<template>
  <!---------- 查询表单form begin ----------->
  <a-form class="smart-query-form">
    <a-row class="smart-query-form-row">
      <a-form-item label="模型" class="smart-query-form-item">
        <a-select ref="select" v-model:value="queryForm.apiId" style="width: 200px" placeholder="请选择模型" @change="modelChange">
          <a-select-option v-for="item in modelList" :key="item.apiId" :value="item.apiId">{{ item.apiName }}</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item class="smart-query-form-item">
        <a-button @click="resetQuery" class="smart-margin-left10">
          <template #icon>
            <ReloadOutlined />
          </template>
          重置
        </a-button>
      </a-form-item>
    </a-row>
  </a-form>
  <!---------- 查询表单form end ----------->

  <div class="monitor-card">
    <div class="table">
      <a-card size="small" class="card" :bordered="false" :hoverable="true">
        <a-row class="smart-table-btn-block">
          <div class="smart-table-operate-block">监控时长：{{ intervalTime }} 秒</div>
        </a-row>
        <a-table
          size="small"
          class="card"
          :dataSource="attrList"
          :columns="columns"
          rowKey="attrId"
          bordered
          :loading="tableLoading"
          :pagination="false"
        />
      </a-card>
    </div>
    <div class="winlist">
      <a-card size="small" class="card" :bordered="false" :hoverable="true">
        <div class="win-title">实时数据</div>
        <div class="win-list" v-if="messageList.length > 0">
          <div class="win-item" v-for="(item, index) in messageList" :key="index">
            <div class="time">{{ item.time }}</div>
            <div class="content">{{ item.content }}</div>
          </div>
        </div>
        <div class="win-no-data" v-else>- 暂无数据 -</div>
      </a-card>
    </div>
  </div>
</template>
<script setup>
  import { ref, onMounted, onUnmounted, watch } from 'vue';
  import { useRoute } from 'vue-router';
  import { PAGE_SIZE_OPTIONS } from '/@/constants/common-const';
  import { PageMixin } from '/@/utils/mixin';
  import { iotApi } from '/@/api/plat/dataApi';
  import { iotApi as iotAttrApi } from '/@/api/plat/dataApiAttr';
  import MqttJS from './mqtt.js';
  import { dateFormat } from '/@/utils/date.js';

  const { tableLoading, tableData, resetQueryForm } = PageMixin();
  // 表格列
  const route = useRoute();
  const columns = ref([
    {
      title: '名称',
      dataIndex: 'attrName',
      ellipsis: true,
    },
    {
      title: '编码',
      dataIndex: 'attrCode',
      ellipsis: true,
    },
    {
      title: '类型',
      dataIndex: 'dataType',
      ellipsis: true,
    },
    {
      title: '值',
      dataIndex: 'data',
      ellipsis: true,
    },
  ]);
  let timeInterval = null;
  let intervalTime = ref(0);

  const defalutData = {
    apiId: undefined,
  };

  let queryForm = ref(Object.assign({}, defalutData));

  const modelList = ref([]);
  const attrList = ref([]);
  const messageList = ref([]);

  const mqttIP = import.meta.env.VITE_APP_MQTT;
  let mqttInfo = {
    ipAddress: mqttIP,
    port: 8083,
  };
  let MqttTarget = null;
  // 重置查询条件
  function resetQuery() {
    clearInter();
    queryForm.value = resetQueryForm(defalutData);
  }
  // 执行定时器
  function modelChange(val) {
    clearInter();
    // 先请求对应的点位数据，然后根据对应的点位数据，进行表格的监听，即数据的刷新
    getAttrList();
    // 连接mqtt
    const model = modelList.value.find((m) => m.apiId === val) || {};
    mqttInfo.topicList = [{ topic: model.apiTopic }];
    MqttJS.createConnection(mqttInfo).then((res) => {
      MqttTarget = res;
      MqttTarget.on('message', (topic, message) => {
        const row = JSON.parse(MqttJS.Uint8ArrayToString(message));
        for (let item of attrList.value) {
          item.data = row[item.attrCode];
        }

        if (messageList.value.length > 30) {
          messageList.value.pop();
        }
        messageList.value.unshift({
          time: dateFormat(),
          content: row,
        });
      });
    });
    // 计时
    timeInterval = setInterval(() => {
      intervalTime.value += 1;
    }, 1 * 1000);
  }
  // 销毁定时器
  function clearInter() {
    intervalTime.value = 0;
    messageList.value = [];
    clearInterval(timeInterval);
    if (MqttTarget) {
      MqttTarget.end(true, () => {
        console.log('MQTT client disconnected and destroyed');
      });
      MqttTarget = null;
    }
  }
  function getAttrList() {
    tableLoading.value = true;
    iotAttrApi.queryList({ apiId: queryForm.value.apiId }).then(({ data }) => {
      attrList.value = data;
      tableLoading.value = false;
    });
  }
  function getModelList() {
    iotApi.queryList({ deviceId: queryForm.value.deviceId }).then(({ data }) => {
      modelList.value = data;
    });
  }

  onMounted(getModelList);
  // 页面初始化判断路由当中是否有设备和设备组的信息
  // 页面销毁的时候，清空定时器
  onUnmounted(clearInter);
</script>

<style scoped>
  .monitor-card {
    display: flex;
    height: calc(100% - 62px - 20px);
    justify-content: space-between;
    overflow: hidden;
  }
  .table {
    width: 70%;
    height: 100%;
  }
  .winlist {
    width: calc(30% - 20px);
    height: 100%;
  }
  .card {
    height: 100%;
  }
  ::v-deep .ant-card-body {
    height: 100%;
  }
  .win-title {
    font-size: 18px;
    height: 35px;
    color: #000;
    text-align: center;
    padding-bottom: 15px;
    border-bottom: 1px solid #eee;
  }
  .win-list {
    padding: 30px 15px 0;
    height: calc(100% - 35px);
    overflow-y: scroll;
  }
  .win-item {
    border-radius: 5px;
    border: 1px solid #eee;
    box-shadow: 0px 0px 10px #ddd;
    padding: 20px;
    margin-bottom: 20px;
  }
  .win-item .time {
    font-size: 14px;
    color: #000;
    font-weight: 700;
  }
  .win-item .content {
    font-size: 16px;
    color: #333;
    margin-top: 10px;
  }
  .win-no-data {
    margin-top: 20px;
    color: #666;
    text-align: center;
  }
</style>
